package com.zjpavt.client.hal;

import com.zjpavt.client.Connection;
import com.zjpavt.client.command.CommandPusher;
import com.zjpavt.client.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DecimalFormat;

/**
 * 温度监控控制类
 *
 * @author cjp
 */
public class SystemInnerTemperatureSensor {

    private static final Logger log = LoggerFactory.getLogger(SystemInnerTemperatureSensor.class);
    private static final SystemInnerTemperatureSensor instance = new SystemInnerTemperatureSensor();

    /**
     * GPS group name
     */
    private static final String INI_GPS_GROUP = "gps_data";

    /**
     * temperature keyName in GPS group
     */
    private static final String INI_TEMPERATURE_KEY = "temp";
    /**
     * 低温阈值
     */
    private static final int TMP_THRESHOLD_LOW_DEFAULT = 55;
    private static final String TMP_THRESHOLD_LOW_DEFAULT_STRING = "55";
    private static final DecimalFormat TEMPERATURE_LIMIT_FORMAT = new DecimalFormat("00");
    private static final DecimalFormat TEMPERATURE_FORMAT = new DecimalFormat("0.00");
    /**
     * 温度检测间隔10,000ms
     */
    private static final int TMP_DETECT_PERIOD = 10;

    /**
     * 温度报警间隔时间不得小于 3600 s
     */
    private static final int TEMPERATURE_ALARM_MIN_TIME = 3600 * 1000;
    /**
     * 低温阈值
     */
    private volatile int mTmpThresholdLow = TMP_THRESHOLD_LOW_DEFAULT;

    /**
     * 上一次发送温度异常告警时间
     */
    private static volatile long lastAlarmTime = 0;

    /**
     * 记录上次的状态
     */
    private int mLastStatus = -1;

    private SystemInnerTemperatureSensor() {
        init();
    }

    public static SystemInnerTemperatureSensor getInstance() {
        return instance;
    }

    /**
     * 初始化获取温度阈值，温度，并开启温度监控定时器
     */
    private void init() {
        try {
            String tmpThresholdLow = PropertiesUtil.getPropertiesDefault(Consts.KEY_TMP_THRESHOLD_LOW,TMP_THRESHOLD_LOW_DEFAULT_STRING);
            mTmpThresholdLow = Integer.parseInt(tmpThresholdLow);
        } catch (Exception e) {
            log.error(LoggerUtil.convertException2String(e));
            mTmpThresholdLow = TMP_THRESHOLD_LOW_DEFAULT;
        }
    }

    /**
     * 获取格式化后温度传感器温度
     *
     * @return 温度
     */
    public String getFormattedTmp() {
        double tempDouble = getCurrTmp();
        //单位摄氏度
        String s = TEMPERATURE_FORMAT.format(tempDouble);
        return s;
    }

    public int getTmpThresholdLow() {
        return mTmpThresholdLow;
    }

    public String getTmpThresholdLowFormat() {
        return TEMPERATURE_LIMIT_FORMAT.format(mTmpThresholdLow);
    }
    /**
     * 设置温度阈值
     * @param tmpThresholdLow 温度阈值
     */
    public void setTmpThreshold(int tmpThresholdLow) {
        try {
            PropertiesUtil.setPropertyOrReplaceDefault(Consts.KEY_TMP_THRESHOLD_LOW, String.valueOf(tmpThresholdLow));
            mTmpThresholdLow = tmpThresholdLow;
        } catch (IOException e) {
            log.error(LoggerUtil.convertException2String(e));
        }
    }

    /**
     * 返回温度为double  30.0
     * @return 温度 获取温度传感器温度
     */
    public double getCurrTmp() {
        double tmp = 0;
        try {
            String temperatureValueStr = FileUtil.readFromFile(ClientConfig.TMP_SENSOR_DEVICE_FILE_PATH);
            tmp = Double.parseDouble(temperatureValueStr.trim()) / 1000;
            if (tmp > this.mTmpThresholdLow && lastAlarmTime + TEMPERATURE_ALARM_MIN_TIME < System.currentTimeMillis()) {
                lastAlarmTime = System.currentTimeMillis();
                String sTemp = TEMPERATURE_FORMAT.format(tmp);
                String sThreshold = getTmpThresholdLowFormat();
//				温度异常告警
                CommandPusher.AlarmPush(Connection.getInstance(), "<T_" + sTemp + "_"+ sThreshold +"_ALARM>");
            }
        } catch (FileNotFoundException e) {
            log.error(e.getMessage());
            return Consts.VALUE_INVALID;
        } catch (Exception e) {
            log.error(LoggerUtil.convertException2String(e));
            return Consts.VALUE_INVALID;
        }
        return tmp;
    }
}
